package cn.edu.nuc.wordsbook;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class SQLiteOperationHelper extends SQLiteOpenHelper {

	SQLiteDatabase db = getWritableDatabase();

	public SQLiteOperationHelper(Context context, String name,
			CursorFactory factory, int version) {
		super(context, Constant.DB_NAME, factory, version);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		db.execSQL("CREATE TABLE IF NOT EXISTS " + Constant.TABLEName + "("
				+ Constant.ID + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
				+ Constant.ENGLISH + " text UNIQUE NOT NULL, " + Constant.TRANSLATION + " text NOT NULL,"
				+ Constant.LASTDATE + " text ," + Constant.MILLDATE + " long )");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub

	}

	public long insert(ContentValues values) {
		long flag = db.insert(Constant.TABLEName, null, values);
		return flag;
	}

	public Cursor query(String orderBy) {
		Cursor c = db.query(Constant.TABLEName, null, null, null, null, null,
				orderBy);
		return c;
	}

	public Cursor queryByid(String id) {
		Cursor c = db.query(Constant.TABLEName, null, "_id=" + id, null, null,
				null, null);
		return c;
	}
	
	public boolean update(Long id, ContentValues values) {
		String whereClause = "_id=?";
		String[] whereArgs = { String.valueOf(id) };
		try {
			db.beginTransaction();
			db.update(Constant.TABLEName, values, whereClause, whereArgs);
			db.setTransactionSuccessful();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			db.endTransaction();
		}

		return true;
	}

}
